#!/usr/bin/perl
#
# Test client driver for the Linux Counter
#

use LWP;
use HTTP::Request::Common;
use Time::HiRes qw(time);

$count = 10;
$hostname = $ENV{COUNTER_HOST};
$url = "cgi-perl/validate.pl";
# What to look for in the result to see if it is Good
$okstring = "/person-counter.pl/";

while ($ARGV[0] =~ /^-/) {
    $opt = shift;
    if ($opt eq "-h") {
	$hostname = shift;
    } elsif ($opt eq "-c") {
	$count = shift() + 0;
    }
}
print "Asking $hostname for $url $count times\n";

$ua = LWP::UserAgent->new;
print "Timeout is ", $ua->{timeout}, "\n";

for $testix (1..$count) {
    $sumtime += onetest();
    ++ $testcount;
}
printf "Average time: %4.2f\n", $sumtime / $testcount;

sub onetest {
    $testid = int(rand(10000));
    
    $request = POST "http://$hostname/$url",
         [
	  sendreplyto => "someone.$testid\@msn.com",
	  name => 'Test person',
	  email => 'someone@nospam.example.org',
	  city => 'Kuala Lumpur',
	  state => 'Shenanigan',
	  country => 'LK',
	  'started-month' => 'jan',
	  'started-year' => '99',
	  usage => 'Work',
	  'may-publish' => 'Yes',
	  ];
    if ($DEBUG) {
	print "Request is:\n";
	print $request->as_string();
    }
    $starttime = time();
    $response = $ua->request($request);
    $usedtime = time() - $starttime;
    
    if ($response->is_success) {
	if ($response->content =~ /$okstring/) {
	    print "Response:\n";
	    print $response->content;
	    die "Test failed - non-OK response\n";
	}
	if ($DEBUG) {
	    print "Response:\n";
	    print $response->content;
	}
	print "Response time was $usedtime seconds\n";
    } else {
	print "Error:\n";
	print $response->error_as_HTML;
	die "Test failed - HTTP error\n";
    }
    $usedtime;
}


